package com.sayimo.maker.mall.orders.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.common.AbstractBaseService;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.activity.dao.BaseCutDetailDao;
import com.sayimo.maker.activity.dao.BaseGroupBuyDao;
import com.sayimo.maker.activity.dao.BaseSeckillGoodsDao;
import com.sayimo.maker.activity.vo.BaseCutDetail;
import com.sayimo.maker.mall.goods.dao.GoodsListInterfaceDao;
import com.sayimo.maker.mall.goods.service.GoodsNormsInfoInterfaceSerice;
import com.sayimo.maker.mall.orders.dao.OrdersGoodsInfoInterfaceDao;
import com.sayimo.maker.mall.orders.service.OrdersGoodsInfoInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersListInterfaceService;
import com.sayimo.maker.mall.orders.vo.GenerateOrdersGoodsParams;
import com.sayimo.maker.mall.orders.vo.OrdersGoodsInfo;
import com.sayimo.maker.user.service.ReceivingAddressInterfaceService;


@Service(value = "ordersGoodsInfoInterfaceService")
public class OrdersGoodsInfoInterfaceImplService extends AbstractBaseService implements OrdersGoodsInfoInterfaceService {

	private static Log logger = LogFactory.getLog(OrdersGoodsInfoInterfaceImplService.class);

	@Resource(name = "ordersGoodsInfoInterfaceDao")
	private OrdersGoodsInfoInterfaceDao ordersGoodsInfoInterfaceDao;

	@Resource(name = "ordersListInterfaceService")
	private OrdersListInterfaceService ordersListInterfaceService;

	@Resource(name = "goodsNormsInfoInterfaceSerice")
	private GoodsNormsInfoInterfaceSerice goodsNormsInfoInterfaceSerice;
	
	@Resource(name = "receivingAddressInterfaceImplService")
	private ReceivingAddressInterfaceService receivingAddressInterfaceService;
	
	@Resource(name="goodsListInterfaceImplDao")
	private GoodsListInterfaceDao goodsListInterfaceDao;

	@Autowired
	private BaseSeckillGoodsDao baseSeckillGoodsDao;
	@Autowired
	private  BaseGroupBuyDao baseGroupBuyDao;
	@Autowired
	private BaseCutDetailDao baseCutDetailDao;
	
	@Override
	public Integer insertOrdersGoodsInfo(GenerateOrdersGoodsParams generateOrdersGoodsParams) throws ServiceException {
		try {
			Map priceMap = goodsNormsInfoInterfaceSerice.getNormsValueInfoForShoppingCart(generateOrdersGoodsParams.getGoodsId(), generateOrdersGoodsParams.getNormsValueId());
			OrdersGoodsInfo ordersGoodsInfo = new OrdersGoodsInfo();
			ordersGoodsInfo.setOrdersId(generateOrdersGoodsParams.getOrdersId());
			ordersGoodsInfo.setGoodsId(generateOrdersGoodsParams.getGoodsId());
			ordersGoodsInfo.setNormsValueId(generateOrdersGoodsParams.getNormsValueId());
			ordersGoodsInfo.setBuyNum(generateOrdersGoodsParams.getBuyNum());
			ordersGoodsInfo.setGoodsFrom(generateOrdersGoodsParams.getGoodsForm());
			ordersGoodsInfo.setSellPrice((BigDecimal)priceMap.get("originalPrice"));
			ordersGoodsInfo.setTransactionPrice((BigDecimal)priceMap.get("preferentialPrice"));
			ordersGoodsInfo.setLogisticsCostId(generateOrdersGoodsParams.getLogisticsCostId());
			ordersGoodsInfo.setCartId(generateOrdersGoodsParams.getCartId());
			ordersGoodsInfo.setIsActivity(generateOrdersGoodsParams.getIsActivity());
			ordersGoodsInfo.setEndAreaCode(generateOrdersGoodsParams.getDefaultEndAreaCode());
			ordersGoodsInfo.setLogistcsCost(new BigDecimal(0));
			String isActivity = "";
			if(generateOrdersGoodsParams.getIsActivity() != null){
				isActivity=generateOrdersGoodsParams.getIsActivity().toString();
			}
			String identifier=generateOrdersGoodsParams.getIdentifier();
			Integer seckillTimesId=generateOrdersGoodsParams.getSeckillTimesId();
			if(isActivity != null && !isActivity.equals("") && isActivity.equals("1") ){
				if(identifier != null&& !identifier.equals("") && (identifier.contains("PT_SPMQ"))){
					//获取秒抢活动商品信息
					Map<String,Object> activityGoodsMap = baseSeckillGoodsDao.querySeckillGoodsInfoByGoodsId(generateOrdersGoodsParams.getGoodsId(),identifier,seckillTimesId);
					//活动价格
					//如果活动价有%为按价格打折，否则为活动价格
					if(activityGoodsMap.get("preferentialPrice").toString().indexOf("%")>=0){
						Double activityPrice=Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString().replaceAll("%", ""));
						Double preferentialPrice=Double.parseDouble(priceMap.get("preferentialPrice").toString());
						
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityPrice*preferentialPrice/100.00));
					}else{
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityGoodsMap.get("preferentialPrice").toString()));
					}
					
				}else if(identifier != null&& !identifier.equals("") && (identifier.contains("PT_KJ_"))){
					//获取砍价活动商品信息
					Map map=new HashMap();
					map.put("identifier", identifier);
					map.put("customerId", generateOrdersGoodsParams.getMemberId());
					List<BaseCutDetail> list=new ArrayList<BaseCutDetail>();
					list=baseCutDetailDao.selectBaseCutDetailByIdentifier(map);
					//砍价活动当前价格
					if( list.get(0).getCurrentPrice().toString().indexOf("%")>=0){
						Double activityPrice=Double.parseDouble( list.get(0).getCurrentPrice().toString().replaceAll("%", ""));
						Double preferentialPrice=Double.parseDouble(priceMap.get("preferentialPrice").toString());
						
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityPrice*preferentialPrice/100.00));
					}else{
						ordersGoodsInfo.setTransactionPrice(new BigDecimal ( list.get(0).getCurrentPrice().toString()));
					}
					
				}else if(identifier != null&& !identifier.equals("") && (identifier.contains("PT_TG_"))){
					//获取团购活动商品信息
					Map<String,Object> activityGoodsMap = baseGroupBuyDao.queryGroupBuyGoodsInfoByGoodsId(generateOrdersGoodsParams.getGoodsId(),identifier);
					//活动价格
					//如果活动价有%为按价格打折，否则为活动价格
					if(activityGoodsMap.get("preferentialPrice").toString().indexOf("%")>=0){
						Double activityPrice=Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString().replaceAll("%", ""));
						Double preferentialPrice=Double.parseDouble(priceMap.get("preferentialPrice").toString());
						
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityPrice*preferentialPrice/100.00));
					}else{
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityGoodsMap.get("preferentialPrice").toString()));
					}
				}else{
					//获取活动商品信息	
					Map<String,Object> activityGoodsMap = goodsListInterfaceDao.queryActivityGoodsInfoByGoodsId(generateOrdersGoodsParams.getGoodsId(),identifier);
						//活动价格
					//如果活动价有%为按价格打折，否则为活动价格
					if(activityGoodsMap.get("preferentialPrice").toString().indexOf("%")>=0){
						Double activityPrice=Double.parseDouble(activityGoodsMap.get("preferentialPrice").toString().replaceAll("%", ""));
						Double preferentialPrice=Double.parseDouble(priceMap.get("preferentialPrice").toString());
						
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityPrice*preferentialPrice/100.00));
					}else{
						ordersGoodsInfo.setTransactionPrice(new BigDecimal (activityGoodsMap.get("preferentialPrice").toString()));
					}
				}
			}
			ordersGoodsInfoInterfaceDao.insertOrdersGoodsInfo(ordersGoodsInfo);
			/*if (ordersGoodsInfo.getIsActivity() == null || ordersGoodsInfo.getIsActivity() != 1 || generateOrdersGoodsParams.getIdentifier().contains("CYBK")) {
				ordersListInterfaceService.updateOrdertotalAmountById(generateOrdersGoodsParams.getOrdersId());
			}
			
			// 更新订单总金额（含运费）
			Double sumMoney = ordersListInterfaceService.orderTotalMoney(new Integer[]{generateOrdersGoodsParams.getOrdersId()});
			ordersListInterfaceService.updateOrderSumMoneyById(generateOrdersGoodsParams.getOrdersId(), sumMoney);*/
			
			return ordersGoodsInfo.getId();
		}catch (DaoException de) {
			throw new ServiceException(de);
		}catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	public List queryOrdersGoodsInfosByBatchCode(String batchCode) throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryOrdersGoodsInfosByBatchCode(batchCode);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public OrdersGoodsInfo queryOrdersGoodsInfoById(Integer id) throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryOrdersGoodsInfoById(id);
		} catch (DaoException de) {
			throw new ServiceException(de);
		}

	}
	
	/**
	 * 
	* @Title: queryOrdersGoodsInfoByOrderId 
	* @Description: 查询订单下商品信息
	* @param orderId
	* @return
	* @throws ServiceException
	* @return List
	* @throws
	 */
	@Override
	public List queryOrdersGoodsInfoByOrderId(Integer orderId)
			throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryOrdersGoodsInfoByOrderId(orderId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	public Integer updateOrderGoodsInfo(OrdersGoodsInfo goodsInfo) throws ServiceException{
		try {
			return ordersGoodsInfoInterfaceDao.updateOrderGoodsInfo(goodsInfo);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	public List<OrdersGoodsInfo> queryOrdersGoodsInfoByOrdersId(Integer ordersId) throws ServiceException {
		try {
			return this.ordersGoodsInfoInterfaceDao.queryOrdersGoodsInfoByOrdersId(ordersId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/** 
	  * @package com.sayimo.school.mall.module.order.service
	  * @author chenpy
	  * @Title:  
	  * @Description: 判断商品是否支持发货到指定地址
	  * @param 
	  * @throws ServiceException
	  * @return Map
	  * @date 2016年5月13日
	  */ 
	public Map queryGoodsLogist(Map<String, Object> param) throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryGoodsLogist(param);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * @package com.sayimo.school.mall.module.order.service
	  * @author 田超
	  * @Title:  
	  * @Description:根据订单后去商品是的属性
	  * @param 
	  * @throws ServiceException
	  * @return List
	  * @date 2016年6月14日
	 */
	@Override
	public List queryGoodsInfoByOrderId(Integer orderId) throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryGoodsInfoByOrderId(orderId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 
	* @Title: updateGoodsStatus 
	* @Author: 田超
	* @Date:日期：2016年6月17日  时间：上午11:29:02
	* @Description: 更新商品的状态
	* @return void
	 * @throws ServiceException 
	* @Version 1.0.0
	 */
	public void updateGoodsStatus(Map<String,Object> paramMap) throws ServiceException{
		try {
			ordersGoodsInfoInterfaceDao.updateGoodsStatus(paramMap);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 
	* @Title: updateGoodsStatus 
	* @Author: 田超
	* @Date:日期：2016年6月17日  时间：上午11:29:02
	* @Description: 查询订单相关信息
	* @return void
	 * @throws ServiceException 
	* @Version 1.0.0
	 */
	@Override
	public List queryInfoByOrderId(Integer orderId) throws ServiceException {
		try {
			return ordersGoodsInfoInterfaceDao.queryInfoByOrderId(orderId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/** 
	  * @package com.sayimo.school.mall.service.ope
	  * @author chenpy
	  * @Title:  insertOrderGoodsInfo
	  * @Description: 添加订单商品
	  * @param 
	  * @throws 
	  * @return int
	  * @date 2016年6月22日
	  */
	@Override
	public void insertPrivoderOrderGoodsInfo(OrdersGoodsInfo goodsInfo)
			throws ServiceException {
		try {
			 ordersGoodsInfoInterfaceDao.insertProviderOrderGoodsInfo(goodsInfo);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	  * @package com.sayimo.school.mall.module.order.dao
	  * @author chenpy
	  * @Title:  
	  * @Description: 查询订单的总金额（没有运费 ）
	  * @param 
	  * @throws 
	  * @return BigDecimal
	  * @date 2016年7月26日
	  */ 
	public BigDecimal getOrdersTotalAmount(Map<String, Object> paramMap) throws ServiceException{
		try {
			return this.ordersGoodsInfoInterfaceDao.getOrdersTotalAmount(paramMap);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	  * @package com.sayimo.school.mall.module.order.dao
	  * @author chenpy
	  * @Title:  
	  * @Description: 查询按件收费的商品的运费最大值
	  * @param 
	  * @throws 
	  * @return Map
	  * @date 2016年7月26日
	  */ 
	public Map getLogisticsGoodsId(Map<String, Object> paramMap) throws ServiceException{
		try {
			return this.ordersGoodsInfoInterfaceDao.getLogisticsGoodsId(paramMap);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
}
